Page({
  data: {
    categories: [],
    activeCategoryId: 0,
    courses: [],
    loading: false
  },
  onLoad() {
    this.getCategories();
  },
  getCategories() {
    wx.request({
      url: 'http://localhost:8080/fmSort',
      success: (res) => {
        if (res.data.code === 200) {
          const categories = res.data.data;
          this.setData({
            categories,
            activeCategoryId: categories[0]?.id || 0
          });
          if (categories.length > 0) {
            this.resetAndLoadCourses(categories[0].id);
          }
        }
      }
    });
  },
  resetAndLoadCourses(categoryId) {
    this.setData({
      courses: [],
      loading: true
    }, () => {
      this.loadAllFmAndFilter(categoryId);
    });
  },
  loadAllFmAndFilter(categoryId) {
    wx.request({
      url: 'http://localhost:8080/fm',
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          const BASE_URL = 'http://localhost:8080';
          const allFm = Array.isArray(res.data.data) ? res.data.data : [];
          const filtered = [];
          const idSet = new Set();
          for (const item of allFm) {
            if (String(item.sort) == String(categoryId) && !idSet.has(item.id)) {
              filtered.push({
                id: item.id,
                title: item.fmTitle,
                image: item.fmPic.startsWith('http') ? item.fmPic : BASE_URL + item.fmPic
              });
              idSet.add(item.id);
            }
          }
          this.setData({
            courses: filtered,
            loading: false
          });
        } else {
          this.setData({ loading: false });
        }
      },
      fail: () => {
        this.setData({ loading: false });
      }
    });
  },
  onCategoryTap(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({ activeCategoryId: categoryId });
    this.resetAndLoadCourses(categoryId);
  },
  onCourseTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/index/pages/fmDetails/fmDetails?id=${id}`
    });
  }
});